<?php
class payment
{
	var $db;
	var $tpl;
	var $page;
	var $pay_uid;
	var $parm;
	
	function payment()
	{
		global $db;
		global $config;
		global $tpl;
		global $buid;
				
		$this -> db     = & $db;
		$this -> tpl    = & $tpl;
		$this ->pay_uid =$buid;
		
		/* if(empty($from_admin))
		{
			$sql = "select pay_uid from ".PUSER." where userid='$buid'";
			$this->db->query($sql);
			$this->pay_uid=$this->db->fetchField('pay_uid');
			if(empty($this->pay_uid)&&$_GET['s']!='admin_info')
				msg("main.php?m=payment&s=admin_info");
		} */
	}
	
	function update_account()
	{
	    $buid=$this->pay_uid;
	    $sql="SELECT password FROM ".MEMBER." WHERE userid='$buid'";
	    $this->db->query($sql);
	    $re=$this->db->fetchRow();
	    if(empty($_POST["pass"]) || empty($_POST["pay_pass"]) || empty($_POST["pay_pass2"]))
	    {
	        return '0';	die;
	    }
	    if($re['password']!=md5($_POST["pass"]))
	    {
	        return '1';	die;
	    }
	    
	    if (isset($_POST['oldpass'])){
	        if (empty($_POST['oldpass'])){
	            return '0';	die;
	        }
	        else{
	            $sql="SELECT pay_pass FROM ".PUSER." WHERE pay_uid='$buid'";
	            $this->db->query($sql);
	            $re=$this->db->fetchRow();
	            if($re['pay_pass']!=md5($_POST["oldpass"]))
	            {
	                return '1';	die;
	            }
	            
	        }
	    }
	    
	    
	    if($_POST["pay_pass"]!=$_POST["pay_pass2"])
	    {
	        return '2';	die;
	    }
	    $sql="UPDATE ".PUSER." SET pay_pass='".md5($_POST['pay_pass'])."' WHERE pay_uid='$buid'";
	    $re=$this->db->query($sql);
	    return '3';
	    
		/* if(!empty($_POST['pay_pass']))
		{
			$pay_pass=md5(trim($_POST['pay_pass']));
			$sql="update ".PUSER." set pay_pass='$pay_pass'
			where pay_uid='".$this->pay_uid."'";
			$this->db->query($sql);
		}
		else
		{
			$sql="update ".PUSER." set name='$_POST[name]',tell='$_POST[tell]',mobile='$_POST[mobile]' where pay_uid='".$this->pay_uid."'";
			$this->db->query($sql);
		} */
	}
	
	function get_payment_statu()
	{	
		//是否开通支付账户
		$pay_uid=$this->pay_uid;
		$sql = "select pay_pass from ".PUSER." where pay_uid='$pay_uid' and pay_pass!=''";
		$this->db->query($sql);
		$re=$this->db->fetchRow();
		return $re;
	}
	
	function payment_base()
	{
		global $config;

		$sql = "select * from ".PUSER." where pay_uid='".$this->pay_uid."'";
		$this->db->query($sql);
		$list = $this->db->fetchRow();
		//var_dump($list);
		//------------已绑定的银行
		$sql = "select * from ".ACCOUNTS." where pay_uid='".$this->pay_uid."'";
		$this->db->query($sql);
		$re = $this->db->fetchRow();
		if($re['pay_uid'])
		{
			$list['bank'] = $re['bank'];
			$list['bank_addr'] = $re['bank_addr'];
			$list['accounts'] = $re['accounts'];
			$list['active'] = $re['active'];
			$list['master'] = $re['master'];
		}
		return $list;
	}
	
	function get_bind_bank($statu=NULL)
	{	
		if($statu==1)
			$sql=" and active=1";
		$sql = "select * from ".ACCOUNTS." where pay_uid='".$this->pay_uid."' $sql ";
		$this->db->query($sql);
		$list = $this->db->getRows();
		return $list;
	}
	function payment_bind()
	{
		$add_time = time();
		$sql = "insert into ".ACCOUNTS." (pay_uid,master,bank,bank_addr,accounts,add_time) values('".$this->pay_uid."','$_POST[master]','$_POST[bank]','$_POST[bank_addr]','$_POST[accounts]','$add_time')";
		$re=$this->db->query($sql);
		return $re;
	}
	
	function add_pickup()
	{
		global $config;
		//-----------验证金额及密码
		$sql = "select cash, pay_pass from ".PUSER." where pay_uid='".$this->pay_uid."'";
		$this->db->query($sql);
		$re = $this->db->fetchRow();
		if($re['pay_pass'] != md5($_POST['pword']))
		{
			return "2";
		}
		if(!is_numeric($_POST['pickup']) || $_POST['pickup']<=0 || $re['cash']<$_POST['pickup'])
		{
			return "1";
		}
		//------------减去费用
		$sql = "update ".PUSER." set cash=cash-".$_POST['pickup'].", unreachable=unreachable+".$_POST['pickup']." 
				where pay_uid='".$this->pay_uid."'";
		$o=$this->db->query($sql);
		
		//------------提现记录表
		$flow_id=date("Ymdhis").rand(0,9);
		$add_time=time();
		$cashflowid=$this->db->lastid();
		$sql = "insert into ".CASHPICKUP." 
			(amount,pay_uid,cashflowid,add_time,bank_id)
			 	values
			('$_POST[pickup]','".$this->pay_uid."','$flow_id','$add_time',$_POST[bank_id])";
		$this->db->query($sql);
		$order_id=$this->db->lastid();
		
		//------------写进流水账
		include("$config[webroot]/module/payment/lang/$config[language].php");
		$sql="insert into ".CASHFLOW." 
		 (`pay_uid`,`order_id`,`price`,`flow_id`,`note`,`time`,statu,type)
		 values 
		 ('".$this->pay_uid."','$order_id','-".$_POST['pickup']."','$flow_id','$note[2]','$add_time',1,1)";
		$this->db->query($sql);
		//--------------
		return $re;
	}
	function pickup_list()
	{
		global $config;
		$sql = "select * from ".CASHPICKUP." where pay_uid='".$this->pay_uid."' order by id desc";
		//==================================
		include_once("$config[webroot]/includes/page_utf_class.php");
	  	$page = new Page;
		$page->listRows=20;
		if (!$page->__get('totalRows'))
		{
			$this->db->query($sql);
			$num=$this->db->fetchRow();
			$page->totalRows = $num["num"];
		}
        $sql .= "  limit ".$page->firstRow.",20";
		//==================================
		$this->db->query($sql);
		$re["list"]=$this->db->getRows();
		$re["page"]=$page->prompt();
		return $re;
	}
	function del_cashflow($deid)
	{
		$sql="update ".CASHFLOW." set display=0 where id='$deid'";
		$this->db->query($sql);
	}
	function payment_cashflow()
	{
		global $config;
		if(isset($_POST['tstart']) && !empty($_POST['tstart']))
			$subsql .= " and time>='".strtotime($_POST['tstart'])."'";
		if(isset($_POST['tend']) && !empty($_POST['tend']))
			$subsql .= " and time<='".(strtotime($_POST['tend'])+60*60*24)."'";
			
		$sql = "select * from ".CASHFLOW." where display=1 and pay_uid='".$this->pay_uid."' $subsql order by id desc";
		//==================================
		include_once("$config[webroot]/includes/page_utf_class.php");
	  	$page = new Page;
		$page->listRows=20;
		if (!$page->__get('totalRows'))
		{
			$this->db->query($sql);
			$num=$this->db->fetchRow();
			$page->totalRows = $num["num"];
		}
        $sql .= "  limit ".$page->firstRow.",20";
		//==================================
		$this->db->query($sql);
		$re["list"]=$this->db->getRows();
		$re["page"]=$page->prompt();
		return $re;
	}
	function payment_pay()
	{
		$sql = "select * from ".PAYMENT." where active=1 order by payment_id";
		$this->db->query($sql);
		$list = $this->db->getRows();
		return $list;
	}
	function payment_online(){
	    $sql = "select * from ".PAYMENT." where active=1 and payment_type!='cod' order by payment_id";
	    $this->db->query($sql);
	    $list = $this->db->getRows();
	    return $list;
	    
	}
	//=================================
	//生成在线支付连接，并做好记录
	function online_pay()
	{
		global $config;
		if ($this->parm['order_id']){
		    
		    //订单的情况
		    $sql="select id, flow_id,pay_uid,statu,order_id,price from ".CASHFLOW." where order_id='{$this->parm['order_id']}' and pay_uid!=0 and statu=1";//验证签名
		    $this->db->query($sql);
		    $re=$this->db->fetchRow();
		    $userid=$re['pay_uid'];
		    $pay_statu=$re['statu'];
		    
		    $amount=trim($this->parm['price'])*1; $time=time();
		    $flow_id=$re['flow_id'];
		    $id=$re['id'];
		    
		}else{
		// 充值的情况    第一步写入流水记录，状态为处理中。
		    $amount=trim($this->parm['price'])*1; $time=time();
		    $flow_id=date("Ymdhis").rand(0,9);
		    include("$config[webroot]/module/payment/lang/$config[language].php");
		$sql="insert into ".CASHFLOW."
			(`pay_uid`,flow_id,`price`,`time`,`note`,`statu`,`type`)
			values
			('".$this->pay_uid."','$flow_id','$amount','$time','$note[1]','1','2')";
		$this->db->query($sql); $id=$this->db->lastid();
		}
		
		
		
		if($this->parm['payment_type']=='tenpay'&&$id)
		{
			$url=$config['weburl']."/main.php?m=payment&s=admin_accounts_base&onlinepaytype=tenpay";
			require_once($config['webroot']."/lib/pay/tenpay/classes/PayRequestHandler.class.php");
			$configs=$this->get_pay_config('tenpay');
			$strDate = date("Ymd");$strTime = date("His");$randNum = rand(1000, 9999);//4位随机数。
			$transaction_id = $configs['tenpay_account'] . $strDate . $strTime.$randNum;/* 财付通交易单号*/
			$reqHandler = new PayRequestHandler();
			$reqHandler->init();
			$reqHandler->setKey($configs['tenpay_key']);
			$reqHandler->setParameter("bargainor_id", $configs['tenpay_account']);	//商户号
			$reqHandler->setParameter("sp_billno", $id);						//商户订单号
			$reqHandler->setParameter("transaction_id", $transaction_id);		//财付通交易单号
			$reqHandler->setParameter("total_fee", $amount*100);				//产品总金额,以分为单位
			$reqHandler->setParameter("return_url", $url);						//返回处理地址
			$reqHandler->setParameter("desc", iconv('utf-8','gb2312',$config['company']));				//产品名称
			//$reqHandler->setParameter("spbill_create_ip", $_SERVER['REMOTE_ADDR']);//用户ip
			$link = $reqHandler->getRequestURL();
			msg($link);

		}
		elseif($this->parm['payment_type']=='alipay'&&$id)
		{
			require_once($config['webroot']."/lib/pay/alipay/lib/alipay_service.class.php");
			$configs=$this->get_pay_config('alipay');
			$parameter = array(
			    //构造要请求的参数数组，无需改动    
				"service"         => "create_direct_pay_by_user",   //交易类型
				"payment_type"    => "1",               			//默认为1,不需要修改
				"partner"         => $configs['partner'], 			//合作商户号
				"_input_charset"  => $configs['input_charset'],   	//字符集，默认为GBK
				"seller_email"    => $configs['seller_email'],    	//卖家邮箱，必填
				"return_url"      => $configs['return_url'],       	//同步返回
				"notify_url"      => $configs['notify_url'],       	//异步返回
				"out_trade_no"    => $flow_id,     					//产品交易流水号，必填（保证唯一性）
				"subject"         => $config['company'],  			//产品名称，必填
				"body"            => $config['company'],     		//产品描述，必填
				"total_fee"       => $amount,       				//产品单价，必填（价格不能为0）
				"show_url"        => $config['weburl'], 			//产品相关网站
				"anti_phishing_key"	=> $anti_phishing_key,//防钓鱼时间戳
				"exter_invoke_ip"	=> $exter_invoke_ip,//获取客户端的IP地址，建议：编写获取客户端IP地址的程序
			);
			
			//建立请求
			
			$alipayService = new AlipayService($configs);
			echo $alipayService->create_direct_pay_by_user($parameter);
		}
		elseif($this->parm['payment_type']=='reapal'&&$id){
		    $bank=$this->parm['bank'];
		    require_once($config['webroot']."/lib/pay/reapal/rongpayto.php");
		    
		}
		
	}
	
	
	
	
	
	//$out_trade_no 本地交易号
	//$trade_no 支付宝交易号
	//交易状态 $trade_status 
	//处理在线友付返回结果。
	//zx新增处理微仓与伙拼的订单
	 function apply_result($out_trade_no,$trade_no=NULL,$trade_status=NULL)
	{
	    global $config;
	    if (strlen($out_trade_no)==14){//伙拼的订单
	        $sql="select status,payment_status,stock_shop,hp_id from ".HUOPINORDER." where order_id='$out_trade_no' limit 1";//验证签名
	        $this->db->query($sql);
	        $re=$this->db->fetchRow();
	        $pay_status=$re['payment_status'];
	        $is_succeed=$re['status'];
	        $stock_shop=$re['stock_shop'];
	        if($pay_status==1&&$is_succeed==1)//处理伙拼订单
	        {
	            $sql="update ".HUOPINORDER." set payment_status='2',status='2',pay_time='".date("Y-m-d H:i:s",time())."' where order_id='".$out_trade_no."' limit 1";
	            $this->db->query($sql);
	            //处理实际伙拼数量 
	            $sql="select sum(num) as true_amount from ".HUOPINORDERPRO." where order_id='$out_trade_no'";
	            $this->db->query($sql);
	            $true_amount=$this->db->fetchField('true_amount');
	            $sql="update ".HUOPIN ." set true_amount=true_amount+{$true_amount} where id={$re['hp_id']}";
	            $this->db->query($sql);
	            return true;
	        }
	    }
	    elseif (strlen($out_trade_no)==15){//微仓的订单
	        $sql="select status,pay_status,stock_shop,member_id from ".MICROSTOCKORDER." where order_id='$out_trade_no' limit 1";
	        $this->db->query($sql);
	        $re=$this->db->fetchRow();
	        $pay_status=$re['pay_status'];
	        $is_succeed=$re['status'];
	        $stock_shop=$re['stock_shop'];
	        $member_id=$re['member_id'];
	        if($pay_status==1&&$is_succeed==1)//处理微仓订单
	        {
	    
	            $sql="update ".MICROSTOCKORDER." set pay_status='2',status='2',pay_time='".date("Y-m-d H:i:s",time())."' where order_id='".$out_trade_no."' limit 1";
	            $this->db->query($sql);
	    
	            //处理微仓库存的
	            $sql="select sku_id,num  from ".MICROSTOCKORDERPRO." where order_id='$out_trade_no'";
	            $this->db->query($sql);
	            $re=$this->db->getRows();
	            foreach ($re as $item){
	               $sql="select 1 from ".MICROSTOCK ." where member_id={$member_id} and sku_id={$item['sku_id']} and stock_shop={$stock_shop} limit 1";
	               $this->db->query($sql);
	               if ($this->db->fetchRow()){
	                   $this->db->query("update ".MICROSTOCK." set num=num+{$item['num']} where member_id={$member_id} and sku_id={$item['sku_id']} and stock_shop={$stock_shop} limit 1 ");
	               }else{
	                   $this->db->query("select pid from ".SETMEAL. " where id={$item['sku_id']} limit 1");
	                   $pid=$this->db->fetchField('pid');
	                   $this->db->query("insert into ".MICROSTOCK." set member_id={$member_id},sku_id={$item['sku_id']},pid={$pid},stock_shop={$stock_shop},num={$item['num']}");
	               }
	            }

			    //放入返利处理队列
			    include_once("$config[webroot]/lib/Httpsqs.php");
			    Httpsqs::put('tarentoOrder',array('order_id'=>$out_trade_no));
	            return true;
	    
	        }
	    }elseif(strlen($out_trade_no)==18){  //膜法伊人订单
	        $sql="select type,direct_rec_mid,member_id,buyPoductNum from ".MAGICORDER." where orderNum='$out_trade_no' limit 1";//验证签名
	        $this->db->query($sql);
	        $re=$this->db->fetchRow();
	        $type = $re['type'];
	        $direct_rec_mid = $re['direct_rec_mid'];
	        $memberId = $re['member_id'];
	        $buyPoductNum = $re['buyPoductNum'];       //购买数量
	        
	        if($type == 0)//处理膜法伊人订单
	        {
	           //修改订单状态
	            $sql="update ".MAGICORDER." set type='1',pay_time='".date("Y-m-d H:i:s",time())."' where orderNum='".$out_trade_no."' limit 1";
	            $this->db->query($sql);
	            
	            //给上级发送红包
	            $sql = "select account from haiou_tarento where member_id='{$direct_rec_mid}' limit 1";
	            $this->db->query($sql);
	            $account = $this->db->fetchField('account');
	            
	            
	            
	            
	            if($account){
	                $new_account = intval($account) + (10 * $buyPoductNum);      //给上级用户分配10元
	                $sqls = "update haiou_tarento set account = ".$new_account." where member_id = ".$direct_rec_mid."";
	                $this->db->query($sqls);
	                
	                $price = $buyPoductNum * 10;
	                
	                //写入收入明细
	                $sql_1="insert into ".TARENTOCASHFLOW.
	                "(member_id,price,type_code,description,extension,create_time) 
	                    VALUES (".$direct_rec_mid.",".$price.",'MAGIC_GET_BONUS','膜法伊人面膜销售分红','admin',".date("Ymdhis").")";
	                
	                $this->db->query($sql_1);
	                
	                include_once($config["webroot"]."/lib/Helper.php");
	                //给直接上级推送红包消息
	                $replaceArrs = [];
	                $param = [
	                    'memberId'=>$direct_rec_mid,
	                    'keyword1'=>$out_trade_no,
	                    'keyword2'=>($buyPoductNum * 30) . '.00元',
	                    'keyword3'=> ($buyPoductNum*10) . '.00元',
	                    'keyword4'=>date("Y年m月d H:i:s"),
	                    'url'=>'http://wx.52ywy.com/?shop='.$direct_rec_mid.'#&ucenter/balance'
	                ];
	                Helper::pushMessage('magicSuccess', $replaceArrs, $param);
	            }
	            return true;
	        }
	    }
		
		$sql="select status,pay_status,stock_shop,member_id,order_type,ms_id,ship_addr,ship_name,cost,cpns_price,freight,ms_Freight_risk,total_ms_taxation from ".ORDER." where order_id='$out_trade_no' limit 1";//验证签名
		
		$this->db->query($sql);
		$re=$this->db->fetchRow();
		$pay_status=$re['pay_status'];
		$is_succeed=$re['status'];
		$stock_shop=$re['stock_shop'];
		$member_id=$re['member_id'];
		$order_type=$re['order_type'];
		$belondShopId = $re['ms_id'];
		//单笔支付商品金额
		$oneOrderCost = $re['cost'];
		//支付总金额
		$allMoney = $re['cost'] + $re['cpns_price'] + $re['freight'] + $re['ms_Freight_risk'] + $re['total_ms_taxation'];
		
		
		if($is_succeed==1)//如果验证成功,并且流水表中的记录为新提交
		{	
			if($pay_status==1)//如果是支付订单的情况
			{
			    include_once($config['webroot']."/module/product/includes/plugin_order_class.php");
			    $order = new order();
			    
			    $order->set_order_statu($out_trade_no,2);
			    
				$sql="update ".ORDER." set pay_status='2',status='2',pay_time=".time()." where order_id='".$out_trade_no."'";
				$this->db->query($sql);
				
				$sql="insert into ".ORDERLOG."(order_id,admin_id,admin_name,text,behavior,result) VALUES ('$out_trade_no','','','订单付款完成，交易号:$trade_no','付款','success')";
				$this->db->query($sql);

			   //处理库存的
			    include_once($config['webroot']."/module/product/inventory_api.php");
			    $sql="select a.product_id,a.num as nums,a.microstock_num,a.price,a.member_id,a.active_id,b.stock_relations from ".ORPRO." as a left join ".SETMEAL." as b on a.product_id=b.id where a.order_id='$out_trade_no'";	// and a.supplier_id=0
			    $this->db->query($sql);
			    $re=$this->db->getRows();

				// 获取全返活动的产品ID集合
				$quanfanProductIDS = array();//Api::callItemApi('Quanfan', 'getProductIDS');
// 				$quanfanOrderTotal = 0;
				$commonOrderTotal = 0;

			    foreach($re as $val)
			    {
			        if(!empty($val['nums']))
			        {
			            //减库存zxzxzx减库存
			            reduceInventory($val['product_id'].'_'.$val['stock_relations'],$val['nums'],$out_trade_no,$stock_shop);
			        }
			        if (!empty($val['microstock_num'])){
			            //微仓出库处理
			            $this->db->query("select pid from ".SETMEAL. " where id={$val['product_id']} limit 1");
			            $pid=$this->db->fetchField('pid');
			            $this->db->query("insert into ".MICROSTOCKOUT." set member_id={$member_id},order_id='{$out_trade_no}',sku_id={$val['product_id']},pid={$pid},stock_shop={$stock_shop},num={$val['microstock_num']}");
			            
			        }
// 					if($val['active_id'] == 1){
// 					    $quanfanOrderTotal += $val['price'] * $val['nums'];
// 					}else{
						$commonOrderTotal += $val['price'] * $val['nums'];
// 					}
					
					// TODO: test
//					$sql="insert into ".ORDERLOG."(order_id,admin_id,admin_name,text,behavior,result) VALUES ('$out_trade_no','','','active_id:{$val['active_id']}','付款','success')";
//					$this->db->query($sql);
			    }
                
			    //查询用户是否使用优惠券结算
			    $sql = "select * from ".ORDER." where order_id = '{$out_trade_no}'";
			    $this->db->query($sql);
		        $strs=$this->db->fetchRow();
			    if($strs['cpns_price'] > 0){
// 					if($quanfanOrderTotal > 0 && $commonOrderTotal > 0){
// 						$cnp_quan = ceil(($quanfanOrderTotal/($quanfanOrderTotal+$commonOrderTotal)) * $strs['cpns_price']);
// 						$quanfanOrderTotal = $quanfanOrderTotal - $cnp_quan;
// 						$commonOrderTotal = $commonOrderTotal - ($strs['cpns_price']-$cnp_quan);
// 					}elseif($quanfanOrderTotal > 0){
// 						$quanfanOrderTotal = $quanfanOrderTotal - $strs['cpns_price'];
// 					}elseif($commonOrderTotal > 0){
						$commonOrderTotal = $commonOrderTotal - $strs['cpns_price'];
// 					}
			    }

				// 查看是否是第一单
				$sql="select COUNT(member_id) AS total_num from ".ORDER." where status > 1 and pay_status > 1 and active_id != 3  and  member_id={$member_id} AND master_order_id=''";//验证签名
				$this->db->query($sql);
				$orderNum = $this->db->fetchRow();
                
				// 如果购买了普通区产品，并且是第一单，则可以参与99返活动
				if($commonOrderTotal > 0 && $orderNum['total_num'] <= 1){
					$quanfanOrderData = [
							'memberId'	=> $member_id,
							'orderId'	=> $out_trade_no,
							'shopId'	=> $belondShopId,
							'orderType'	=> 2,
							'price'		=> $commonOrderTotal
					];

					// TODO: test
					$env = RUN_ENV;
					$sql="insert into ".ORDERLOG."(order_id,admin_id,admin_name,text,behavior,result) VALUES ('$out_trade_no','','','testxxxx:{$env}commonOrderTotal','付款','success')";
					$this->db->query($sql);

					// 添加全返订单
					Api::callItemApi('Quanfan', 'addOrder', $quanfanOrderData);
				}
			    
				// 添加全返活动订单
// 				if($quanfanOrderTotal > 0){
// 					$quanfanOrderData = [
// 						'memberId'	=> $member_id,
// 						'orderId'	=> $out_trade_no,
// 						'shopId'	=> $belondShopId,
// 						'orderType'	=> 1,
// 						'price'		=> $quanfanOrderTotal
// 					];

// 					// TODO: test
// 					$env = RUN_ENV;
// 					$sql="insert into ".ORDERLOG."(order_id,admin_id,admin_name,text,behavior,result) VALUES ('$out_trade_no','','','testxxxx:{$env}quanfanOrderTotal','付款','success')";
// 					$this->db->query($sql);

// 					// 添加全返订单
// 					Api::callItemApi('Quanfan', 'addOrder', $quanfanOrderData);
// 				}
			    
			    if($order_type<3){//微店订单不参与合伙人结算
    			    //放入返利处理队列
    			    include_once("$config[webroot]/lib/Httpsqs.php");
    			    Httpsqs::put('tarentoOrder',array('order_id'=>$out_trade_no));
			    }else{
			        
			        // TODO: test
			        $env = RUN_ENV;
			        $sql="insert into ".ORDERLOG."(order_id,admin_id,admin_name,text,behavior,result) VALUES ('$out_trade_no','','','payment_class.php 610-line','付款','success')";
			        $this->db->query($sql);
			        
			        
		            //给用户推送消息
		            $replaceArr = [];
		            //订单商品信息
		            $sql = "select product_name from ".ORPRO." where order_id='{$out_trade_no}' limit 1";
		            $this->db->query($sql);
		            $productName = $this->db->fetchField('product_name');
		            
		            //查询订单支付总金额
		            
		            $param = [
		                'memberId'=>$re['member_id'],
		                'orderProductPrice'=>$allMoney,
		                'orderProductName'=>$productName,
		                'orderAddress'=>$re['ship_name'].','.$re['ship_addr'],
		                'orderName'=>$out_trade_no,
		                'url'=>'http://wx.52ywy.com/?shop='.$re['ms_id'].'#&cart/orderdetail/?id='.$out_trade_no
		            ];
		            include_once($config["webroot"]."/lib/Helper.php");
		            Helper::pushMessage('orderPaySuccess', $replaceArr, $param);
		            
		            //微店订单，加销售额
// 		            include_once($config['webroot']."/module/micro_shop/includes/plugin_micro_shop_class.php");
// 		            $microShop = new MicroShop();
// 		            $microShop->updateSalesInfoByOrder($out_trade_no);
		            
			    }
// 			    $this->check_activity($out_trade_no,$member_id);//检查是否符合参与活动的条件
			    return true;
			    
			}else{//充值的情况
			    
			 /*    $total_fee = $re['price'];
			    $sql="update ".CASHFLOW." set statu='4' where flow_id='$out_trade_no'";
			    $this->db->query($sql);
			    
			    $sql="update ".PUSER." set cash=cash+$total_fee where userid='$userid'";
			    $this->db->query($sql);
			    return TRUE; */
			}
		}
		else
			return NULL;
	}
	
	
	/**
	 * 处理开店支付后的结果
	 * @param unknown $out_trade_no
	 * @param string $trade_no
	 * @param string $trade_type
	 */
	function apply_shop($out_trade_no,$trade_no=NULL,$cash_fee,$trade_type){
	    global $config;
	    include_once($config['webroot']."/module/micro_shop/includes/plugin_micro_shop_class.php");
	    $shopNotify=explode('-', $out_trade_no);//分解传递过来的支付回调
	    $memberId=$shopNotify[1];//memberID
	    $level=$shopNotify[2];//级别
	    $microShop = new MicroShop();
	    if (empty($level)||empty($memberId)){
	        return false;
	    }
	    
        //查询店铺数据
        $shopInfo = $microShop->get_shop_info($memberId);
        if (!empty($shopInfo)) {
    	    if ($level==3){ // 开店的情况
                $payInfo = array(
                    'admin_name' => "顾客",
                    'payment_name' => $trade_type,
                    'text' => "支付流水号：".$trade_no,
                    'price'=> $cash_fee,
                    'behavior' => "开店"
                );
                return $microShop->create_shop($memberId,array(),$payInfo,$level);
    	    }else {
    	        if ($shopInfo['status'] == 0) {//直接开红人馆或首席
    	            $payInfo = array(
    	                'admin_name' => "系统自动",
    	                'payment_name' => $trade_type,
    	                'text' => "支付流水号：".$trade_no,
    	                'price'=> 0,
    	                'behavior' => "用户直接开".($level==1?"首席":"红人").",先成为会员"
    	            );
    	            $res = $microShop->create_shop($memberId,array(),$payInfo,$level);
    	            if($res){
    	                $payInfo = array(
    	                    'admin_name' => "顾客",
    	                    'payment_name' => $trade_type,
    	                    'text' => "支付流水号：".$trade_no,
    	                    'price'=> $cash_fee,
    	                    'behavior'=>"店铺升级到".($level==1?"首席":"红人")
    	                );
    	                $rs = $microShop->upgrade_shop($memberId, $level,$payInfo);
    	                if($rs && $level==1){//升级首席后，则去掉升级权利
    	                    $sql = "update ".TARENTO." set can_upgrade_shop=0 where member_id={$memberId}";
    	                    $this->db->query($sql);
    	                }
    	                return $rs;
    	            }
    	        } elseif ($shopInfo['status'] == 1) {//升级的情况
        	        $payInfo = array(
        	            'admin_name' => "顾客",
        	            'payment_name' => $trade_type,
        	            'text' => "支付流水号：".$trade_no,
        	            'price'=> $cash_fee,
        	            'behavior'=>"店铺升级到".($level==1?"首席":"红人")
        	        );
        	        $rs = $microShop->upgrade_shop($memberId, $level,$payInfo);
        	        if($rs){//升级后，则去掉升级权利
        	            $sql = "update ".TARENTO." set can_upgrade_shop=0 where member_id={$memberId}";
        	            $this->db->query($sql);
        	        }
        	        return $rs;
    	        }
    	    }
        }
        
        return false;
	}
	
	function get_pay_config($type)
	{
		global $config;
		$sql="select * from ".PAYMENT." where payment_type='$type'";
		$this->db->query($sql);
		$re=$this->db->fetchRow();
		$re=unserialize($re['payment_config']);
		foreach($re as $v)
		{
			$name=$v['name'];
			$cn[$name]=$v['value'];
		}
		if($type=='alipay')
		{
			$cn['sign_type']    = 'MD5';
			$cn['input_charset']= 'utf-8';
			$cn['transport']    = 'http';
			$cn['return_url']   = $config['weburl']."/notify/redirect_alipay.php";
			$cn['notify_url']   = $config['weburl']."/notify/alipay.php";
		}
		return $cn;
	}
	function check_chongka($card_id,$card_pwd){
	    $t=time();
	    $sql="SELECT `id`, `type`,`stime`,`etime`,`total_price`  FROM  ".PAYCARD."  WHERE card_num='$card_id' and `password`='$card_pwd' and statu='0' limit 1";
	    $this->db->query($sql);
	    $re=$this->db->fetchRow();
	    if ($re['stime']!=0){
	        if ($re['stime']>$t){
	            return '-1';
	        }
	    }
	    if ($re['etime']!=0){
	        if ($re['etime']<$t){
	            return '-2';
	        }
	    }
	    return $re;
	}
	/**
	 * @param 小包参与双12的活动 $order_id
	 */
	function check_activity($order_id,$member_id){
	    global $config;
	    $sql=" select shipping_id from ".ORDER. " where order_id={$order_id} limit 1";
	    $this->db->query($sql);
        if ($this->db->fetchField('shipping_id') == '7') {
            include_once ("$config[webroot]/lib/Rpc.php");
            $res = Rpc::getData('user', 'Prize', 'addTakePrizeNumber', array(
                json_encode(array(
                    'prizeCode' => '1212',
                    'memberId' => $member_id,
                    'number' => 2
                ))
            )); // 调用增加活动次数api
        }
	    
	}
}
?>
